package com.eryos.android.cigarettecounter.database;

import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.util.Log;

import com.eryos.android.cigarettecounter.beans.SmokeTime;

/**
 * Project : CigaretteCounter Author : Olivier Combe URL : http://eryos.fr/CigaretteCounter/
 * 
 * Copyright(C)2011 - Olivier Combe
 * 
 * Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 * @version \$Revision.*\$
 * @author Olivier Combe
 */
public class DailyAdapterImpl {

    private final CigaretteDatabase currentDatabase;

    /**
     * Default constructor.
     * 
     * @param db
     *            associated to the current adapater.
     */
    public DailyAdapterImpl(final CigaretteDatabase db) {
        currentDatabase = db;
    }

    /**
     * @return the number of cigarettes smoked this day.
     */
    public int getDailyCount() {
        Log.i(getClass().getSimpleName(), "get Daily Count");
        String sqlQuery = "SELECT   strftime('" + DBTools.DATE_FORMAT + "', smoke_time), count(1)" + "FROM     "
                + DBConnector.DATABASE_TABLE + " " + "WHERE    strftime('" + DBTools.DATE_FORMAT + "', smoke_time) = "
                + DBFields.THIS_DAY + " " + "GROUP BY strftime('" + DBTools.DATE_FORMAT + "', smoke_time);";

        int res = 0;

        Cursor mCursor = currentDatabase.executeQuery(sqlQuery);

        if (mCursor != null && mCursor.getCount() > 0) {
            mCursor.moveToFirst();
            try {
                res = mCursor.getInt(1);
            } catch (CursorIndexOutOfBoundsException e) {
                Log.w(getClass().getSimpleName(), "get Daily Count", e);
            }
        }

        return res;
    }

    /**
     * @return the time since the last cigarette.
     */
    public SmokeTime getDelaySinceLast() {
        Log.i(getClass().getSimpleName(), "get Delay Since Last Cigarette");
        try {
            SmokeTime res = new SmokeTime();

            String sqlQuery = "SELECT strftime('%s', " + DBTools.getNow() + "), strftime('%s',MAX(smoke_time))"
                    + "FROM " + DBConnector.DATABASE_TABLE + ";";

            Cursor mCursor = currentDatabase.executeQuery(sqlQuery);

            if (mCursor != null) {
                mCursor.moveToFirst();

                String now = mCursor.getString(0) + "000";
                String max = mCursor.getString(1) + "000";

                long diff = Long.valueOf(now) - Long.valueOf(max); // milisecond

                long seconds = diff / 1000; // seconds

                int minute2 = (int) (seconds / 60);
                int hour2 = minute2 / 60; // hours
                minute2 = minute2 - 60 * hour2;

                int hour = hour2;
                int minute = minute2;

                hour = hour < 0 ? 0 : hour;
                minute = minute < 0 ? 0 : minute;

                if (Long.valueOf(max) <= Long.valueOf(now)) {
                    // if (new Long(max) <= new Long(now)) {

                    int day = 0;
                    if (hour > 24) {
                        day = hour / 24;
                    }
                    hour = hour - day * 24;

                    res.setDay(day);
                    res.setHour(hour);
                    res.setMinute(minute);
                    res.setSeconds(0);
                    res.genTotalMinutes();
                } else {
                    Log.d(getClass().getSimpleName(), "Max is greater than Now !!");
                    res.setHour(0);
                    res.setMinute(0);
                    res.setSeconds(0);
                    res.genTotalMinutes();
                }
            }

            return res;
        } catch (NumberFormatException e) {
            Log.e(getClass().getSimpleName(), "get Delay Since Last", e);
            return new SmokeTime();
        }
    }

}
